import router from "@/router";
import { ElMessage } from "element-plus";
import { usePermissionStore, useUserStore } from "@/stores";

const WHITE_LIST = ["/auth/login", "/auth/register", "/"];

router.beforeEach(async (to, from, next) => {
  console.log("路由导航 - 从:", from.path, "到:", to.path);
  console.log(
    "当前所有路由:",
    router.getRoutes().map((r) => ({ name: r.name, path: r.path }))
  );
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();

  // 尝试从存储恢复路由
  if (userStore.isLoggedIn && !permissionStore.routesGenerated) {
    const restored = permissionStore.restoreRoutesFromStorage();
    console.log("尝试从存储恢复路由:", restored ? "成功" : "失败");

    // 如果恢复成功，强制重新导航到目标路径
    if (restored) {
      console.log("路由恢复成功，重新导航到:", to.path);
      // 强制重新导航，确保组件正确渲染
      next({ ...to, replace: true });
      return;
    }
  }

  if (userStore.isLoggedIn) {
    console.log("用户已登录");

    // 检查是否已经生成过动态路由
    if (!permissionStore.routesGenerated) {
      try {
        console.log("开始生成动态路由...");
        const accessRoutes = await permissionStore.generateRoutes();
        console.log("生成的可访问路由:", accessRoutes);

        // 确保路由添加完成后再导航
        next({ ...to, replace: true });
        return;
      } catch (error) {
        console.error("生成路由失败:", error);
        ElMessage.error("菜单加载失败，请刷新页面重试");
        next("/");
        return;
      }
    }

    // 正常访问
    next();
  } else {
    console.log("用户未登录");
    if (WHITE_LIST.includes(to.path)) {
      next();
    } else {
      next("/auth/login");
    }
  }
});
